package com.amoby.main.action.order;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.amoby.base.common.BaseAction;
import com.amoby.base.common.Pager;
import com.amoby.base.utils.CommonwealthBankUtil;
import com.amoby.base.utils.DateUtils;
import com.amoby.base.utils.ExcelUtils;
import com.amoby.main.entity.Channel;
import com.amoby.main.entity.SysUsers;
import com.amoby.main.service.AlipayOrderService;
import com.amoby.main.service.ChannelService;

/**
 * Title：AlipayOrderAction
 * Desc：
 * @address http://www.yingmob.com/
 * @author zhaoyy
 * @date 2016-2-26 上午10:19:53
 */
@Controller
public class AlipayOrderAction extends BaseAction {
    private static final Logger logger = LoggerFactory.getLogger(AlipayOrderAction.class);
    @Autowired
    private AlipayOrderService alipayOrderService;
    @Autowired
    private ChannelService      channelService;
    /**
     * 初始化页面
     * @author Lasing 2016-5-30 下午4:46:55
     * @param model
     * @return
     */
    @RequestMapping(value = "/menus/order_mgr.html", method = RequestMethod.GET)
    public String listPage(ModelMap model) {
        String today = DateUtils.getToday("yyy-MM-dd");
        model.put("startDate", today);
        model.put("endDate", today);
        return AD_HTML + "order/order_mgr";
    }

    /**
     * 支付宝活动订单分页查询列表
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/order/list.html", method = RequestMethod.POST)
    public Object list(HttpServletRequest request) {
        SysUsers user = getUser();
        Channel channel = channelService.getChannelByUserId(user.getUserId()); //根据userId获取渠道信息
        Pager pager = createPager(request);
        pager.addParam("shop_name", getRequestParams(String.class, request, "shop_name"));// 商家名称
        pager.addParam("order_num", getRequestParams(String.class, request, "order_num"));// 订单号
        pager.addParam("trade_no", getRequestParams(String.class, request, "trade_no"));// 交易号
        pager.addParam("startDate", getRequestParams(String.class, request, "startDate"));
        pager.addParam("endDate", getRequestParams(String.class, request, "endDate"));
        pager.addParam("alipay_name", getRequestParams(String.class, request, "alipay_name"));// 支付宝用户
        String qState = getRequestParams(String.class, request, "q_state");// 转账状态
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("shop_name", getRequestParams(String.class, request, "shop_name"));
        map.put("order_num", getRequestParams(String.class, request, "order_num"));
        map.put("trade_no", getRequestParams(String.class, request, "trade_no"));
        map.put("startDate", getRequestParams(String.class, request, "startDate"));
        map.put("endDate", getRequestParams(String.class, request, "endDate"));
        map.put("alipay_name", getRequestParams(String.class, request, "alipay_name"));
        if(channel!=null){
            pager.addParam("channelId", channel.getId());   //渠道id
            map.put("channelId", channel.getId());
        }
        if (qState != null) {// 待处理情况(支付成功，未发起转账，未退款)
            if ("1".equals(qState) ) {
                pager.addParam("qState", null);
                pager.addParam("pState", "1");
                pager.addParam("refundStatus", "0");
                pager.addParam("transferStatus", "0");
                pager = alipayOrderService.query(pager,map);
            } else {
                pager.addParam("pState", "1");
                pager.addParam("qState", qState);
                pager = alipayOrderService.query(pager,map);
            }
        } else {
            pager.addParam("pState", "1");
            pager.addParam("qState", qState);
            pager = alipayOrderService.query(pager,map);
        }
        getGridData(pager);
        return getGridData(pager);
    }

    /**
     * 导出支付宝活动订单
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping(value = "/order/order_export.html", method = RequestMethod.GET)
    public void export(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        Map<String, Object> map = new HashMap<String, Object>();
        String startDate = getRequestParams(String.class, request, "startDate");
        String endDate = getRequestParams(String.class, request, "endDate");
        map.put("startDate", getRequestParams(String.class, request, "startDate"));
        map.put("endDate", getRequestParams(String.class, request, "endDate"));
        map.put("order_num", getRequestParams(String.class, request, "orderNum"));
        map.put("trade_no", getRequestParams(String.class, request, "trade_no"));
        map.put("alipay_name", getRequestParams(String.class, request, "alipayName"));
        map.put("shop_name", getRequestParams(String.class, request, "shopName"));
        String qState = getRequestParams(String.class, request, "qState");// 转账状态
        //String pState = getRequestParams(String.class, request, "pState");// 支付状态
        if (qState != null) {// 待处理情况(支付成功，未发起转账，未退款)
            if ("1".equals(qState)) {
                map.put("qState", null);
                map.put("pState", "1");
                map.put("refundStatus", "0");
                map.put("transferStatus", "0");
            } else {
                map.put("pState", "1");
                map.put("qState", qState);
            }
        } else {
            map.put("pState", "1");
            map.put("qState", qState);
        }
        List<Map<String, Object>> lists = alipayOrderService.exportAll(map);
        exports(lists, request, response,startDate,endDate);
    }

    /**
     * 导出支付宝活动订单
     * @param lists
     * @param request
     * @param response
     */
    @SuppressWarnings("rawtypes")
    private void exports(List<Map<String, Object>> lists, HttpServletRequest request, HttpServletResponse response,String startDate,String endDate) {
        List<List<Comparable>> listData = new ArrayList<List<Comparable>>();
        NumberFormat nt = NumberFormat.getPercentInstance();
        // 设置百分数精确度1即保留两位小数
        nt.setMinimumFractionDigits(1);
        // 增加标题行
        listData.add(setHeader());
        for (int i = 0; i < lists.size(); i++) {
            Map<String, Object> map = lists.get(i);
            List<Comparable> list = new ArrayList<Comparable>();
            list.add(map.get("order_num").toString());
            list.add(map.get("trade_no").toString());
            list.add(map.get("pay_time").toString());
            list.add(map.get("bs_id").toString());
            list.add(map.get("bs_name").toString());
            list.add(map.get("alipay_name").toString());
            list.add(map.get("amount").toString());
            list.add(map.get("brokerage").toString());
            double samount = new BigDecimal(map.get("amount").toString()).subtract(new BigDecimal(map.get("brokerage").toString()))
                    .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            list.add(String.valueOf(samount));
            list.add(map.get("commission").toString());
            list.add(map.get("cbState").toString());
            list.add(map.get("refundStatus").toString());
            list.add(map.get("state").toString());
            listData.add(list);
        }
        String fileName ="";
        startDate = startDate.replaceAll("-", ".");
        endDate = endDate.replaceAll("-", ".");
        if(startDate.equals(endDate)){
            fileName = "Orders_"+startDate+"_";
        }else{
            fileName = "Orders_"+startDate+"-"+endDate+"_";
        }
        ExcelUtils.createExcel(request, response, logger, listData, fileName);
    }

    /**
     * 自定义标题栏
     * @return
     */
    @SuppressWarnings("rawtypes")
    private List<Comparable> setHeader() {
        List<Comparable> list = new ArrayList<Comparable>();
        list.add("订单号");
        list.add("交易号");
        list.add("消费时间");
        list.add("商家ID");
        list.add("商家名称");
        list.add("支付宝用户");
        list.add("消费金额");
        list.add("佣金");
        list.add("实际金额");
        list.add("返佣");
        list.add("转账状态");
        list.add("退款状态");
        list.add("支付状态");
        return list;
    }

    /**
     * 支付宝活动订单退款
     * @param request
     * @return
     */
    // @ResponseBody
    // @RequestMapping(value = "/alipay/refundOrder.html", method = RequestMethod.POST)
    // public Object refundOrder(HttpServletRequest request, String orderNum) {
    // Map<String, Object> result = getResultMap();
    // // 订单号
    // if (orderNum == null || "".equals(orderNum)) {
    // result.put(MESSAGE, "获取参数失败！");
    // return result;
    // }
    // try {
    // Map<String, Object> ordermap = iBusinessOrderService.refundOrder(orderNum);
    // return ordermap;
    // } catch (Exception e) {
    // result.put(MESSAGE, "订单退款异常！");
    // getLog(this).error("更新异常！", e);
    // }
    // return result;
    // }
    /**
     * 正向扫码付款退款
     * @author Lasing 2016-2-15 下午3:02:13
     * @param request
     * @param orderNum
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/order/refundOrder.html", method = RequestMethod.POST)
    public Object refundOrder(HttpServletRequest request, String orderNum) {
        Map<String, Object> result = getResultMap();
        // 订单号
        if (orderNum == null || "".equals(orderNum)) {
            result.put(MESSAGE, "获取参数失败！");
            return result;
        }
        try {
            Map<String, Object> ordermap = alipayOrderService.refundOrder(orderNum);
            return ordermap;
        } catch (Exception e) {
            result.put(MESSAGE, "订单退款异常！");
            getLog(this).error("更新异常！", e);
        }
        return result;
    }
    /**
     * 申请退款
     * @author Lasing 2016-2-23 上午10:42:09
     * @param request
     * @param orderNum
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/order/sqrefundOrder.html", method = RequestMethod.POST)
    public Object sqrefundOrder(HttpServletRequest request, String orderNum) {
        Map<String, Object> result = getResultMap();
        // 订单号
        if (orderNum == null || "".equals(orderNum)) {
            result.put(MESSAGE, "获取参数失败！");
            return result;
        }
        try {
            Map<String, Object> ordermap = alipayOrderService.sqrefundOrder(orderNum);
            return ordermap;
        } catch (Exception e) {
            result.put(MESSAGE, "订单申请退款异常！");
            getLog(this).error("更新异常！", e);
        }
        return result;
    }
    
    /**
     * 导出为PDF
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping(value = "/orderOownloadPdf.html", method = RequestMethod.GET)
    public void downloadPdf(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        Map<Object, Integer> inputMap = new HashMap<Object, Integer>();
        Integer billId = getRequestParams(Integer.class, request, "billId");
        inputMap.put("billId", billId);
        Map<String, Object> result = getResultMap();
        List<Map<String, Object>> map = alipayOrderService.queryBsbAccByOrderno(inputMap);
        if (map == null) {
            result.put(RESULT, false);
            result.put(MESSAGE, "下载PDF出错！");
        } else {
            new CommonwealthBankUtil().generatePDF(request, response, map);
            result.put(RESULT, true);
        }
    }

}
